﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Furion;
using Furion.DynamicApiController;
using Furion.UnifyResult;
using LNSServer.Models;
using LNSServer.ViewModels;
using LNSServer.ViewModels.User;
using Mapster;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using SqlSugar;

namespace LNSServer.Controllers
{
    /// <summary>
    /// 用户
    /// </summary>
    [DynamicApiController]
    public class LnsUserController
    {
        private readonly ILogger<LnsUserController> logger;
        private readonly ISqlSugarClient db; // 核心对象：拥有完整的SqlSugar全部功能
        public LnsUserController(ISqlSugarClient sqlSugarClient)
        {
            this.db = sqlSugarClient;
            this.logger = logger;
        }

        /// <summary>
        /// 用户列表
        /// </summary>
        /// <param name="usf"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<IActionResult> List([FromBody] UserSearchForm usf)
        {
            RefAsync<int> total = 0;
            List<User> users = await db.Queryable<User>()
                .Where(tg => tg.IsActive == 1)
                .WhereIF(!string.IsNullOrEmpty(usf.Content), cg => cg.Username.Contains(usf.Content) || cg.Realname.Contains(usf.Content) || cg.Department.Contains(usf.Content) || cg.Email.Contains(usf.Content) || cg.Phone.Contains(usf.Content))
                .ToPageListAsync(usf.PageIndex, usf.PageSize, total);

            UnifyContext.Fill(new { Total = total.Value });
            return new JsonResult(new RESTfulResult<object>
            {
                StatusCode = 200,
                Succeeded = true,
                Data = users,
                Errors = null,
                Extras = UnifyContext.Take(),
                Timestamp = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds()
            });
        }

        /// <summary>
        /// 增加用户
        /// </summary>
        /// <param name="usf"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<IActionResult> Save([FromBody] UserSaveForm usf)
        {
            // 如果名称重复提示不让添加
            bool isExist = await db.Queryable<User>().Where(tg => tg.Username == usf.Username).Where(um => um.IsActive == 1).AnyAsync();
            if (isExist) {
                return new JsonResult(new RESTfulResult<object>
                {
                    StatusCode = -1,
                    Succeeded = false,
                    Data = null,
                    Errors = "该账号已存在",
                    Extras = UnifyContext.Take(),
                    Timestamp = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds()
                });
            }

            User user = await db.Insertable<User>(usf.Adapt<User>()).ExecuteReturnEntityAsync();

            return new JsonResult(new RESTfulResult<object>
            {
                StatusCode = 200,
                Succeeded = true,
                Data = user.Adapt<UserView>(),
                Errors = null,
                Extras = UnifyContext.Take(),
                Timestamp = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds()
            });
        }

        /// <summary>
        /// 删除用户
        /// </summary>
        /// <param name="udf"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<IActionResult> Delete([FromBody] UserDeleteForm udf) {
            await db.Updateable<User>().SetColumns(t => t.IsActive == 0).Where(t => t.Id == udf.Id).ExecuteCommandAsync();

            return new JsonResult(new RESTfulResult<object>
            {
                StatusCode = 200,
                Succeeded = true,
                Data = null,
                Errors = null,
                Extras = UnifyContext.Take(),
                Timestamp = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds()
            });
        }

        /// <summary>
        /// 修改用户
        /// </summary>
        /// <param name="uuf"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<IActionResult> Update([FromBody] UserUpdateForm uuf) {
            // 如果名称重复提示不让添加
            bool isExist = await db.Queryable<User>()
                .Where(u => u.Username == uuf.Username)
                .Where(u => u.Id != uuf.Id)
                .Where(um => um.IsActive == 1).AnyAsync();
            if (isExist)
            {
                return new JsonResult(new RESTfulResult<object>
                {
                    StatusCode = -1,
                    Succeeded = false,
                    Data = null,
                    Errors = "用户名称已存在",
                    Extras = UnifyContext.Take(),
                    Timestamp = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds()
                });
            }

            // 更新user表name字段
            await db.Updateable<User>(uuf.Adapt<User>()).ExecuteCommandAsync();

            return new JsonResult(new RESTfulResult<object>
            {
                StatusCode = 200,
                Succeeded = true,
                Data = uuf,
                Errors = null,
                Extras = UnifyContext.Take(),
                Timestamp = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds()
            });
        }

        /// <summary>
        /// 查看用户
        /// </summary>
        /// <param name="usf"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<IActionResult> Show([FromBody] UserShowForm usf) {
            User user = await db.Queryable<User>()
                .InSingleAsync(usf.Id);
            return new JsonResult(new RESTfulResult<object>
            {
                StatusCode = 200,
                Succeeded = true,
                Data = user,
                Errors = null,
                Extras = UnifyContext.Take(),
                Timestamp = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds()
            });
        }


        /// <summary>
        /// 用户登录
        /// </summary>
        /// <param name="ulf"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<IActionResult> Login([FromBody] UserLoginForm ulf)
        {
            User user = await db.Queryable<User>()
                .Where(u => u.Username == ulf.Username)
                .SingleAsync();
            if (user == null)
            {
                return new JsonResult(new RESTfulResult<object>
                {
                    StatusCode = -1,
                    Succeeded = false,
                    Data = null,
                    Errors = "该账户不存在",
                    Extras = UnifyContext.Take(),
                    Timestamp = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds()
                });
            }

            if (!user.Password.Equals(ulf.Password))
            {
                return new JsonResult(new RESTfulResult<object>
                {
                    StatusCode = -1,
                    Succeeded = false,
                    Data = null,
                    Errors = "密码错误",
                    Extras = UnifyContext.Take(),
                    Timestamp = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds()
                });
            }

            return new JsonResult(new RESTfulResult<object>
            {
                StatusCode = 200,
                Succeeded = true,
                Data = new { Id = user.Id, Realname = user.Realname, Role = user.Role },
                Errors = null,
                Extras = UnifyContext.Take(),
                Timestamp = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds()
            });
        }
    }
}
